 warning off all
clear all
%prepare xp parameter
numTrials =15;
%xpType = input('Please input the type of experiment: anti or pro','s');
%distToScreen = input('please input distance from subject to screen(mm):');%mm
%distToScreen = distToScreen/25.4; %inch
%edfFile = input('enter tracker EDF file name(1 to 8 letters or numbers): ','s');
xpType='pro';
distToScreen=600/25.4;
edfFile='1234567';
%% read image
imageCoin = imread('5yen_coin-back_fixed50.PNG');

[yCoin,xCoin,depthCoin] = size(imageCoin);

%% set up connection to NetStation
 %NetStation('Connect','100.1.1.3',55513);
 %NetStation('Synchronize'); %do Synchronization with SynchLimit being 2.5ms

%% Open a window and prepare for xp
%Screen('Preference', 'ConserveVRAM', 4096)
%VTOTAL = 768;%real height of display
%Screen('Preference', 'VBLEndlineOverride', VTOTAL);
Screen('Preference','SkipSyncTests',1);
Screen ('Preference','VisualDebugLevel',0);
Screen('Preference','SuppressAllWarnings',1);
screenNumber=max(Screen('Screens'));
pixelSize=8;
[winPtr,windowRect]=Screen('OpenWindow',1,[],[],pixelSize);%for desktop
%[winPtr,windowRect]=Screen('OpenWindow',screenNumber,[],[],pixelSize); %for laptop
coinTextureInd = Screen('MakeTexture', winPtr, imageCoin);

angleTarget = [-10,10];
% distToScreen = 23; %inch
wideScreen = 17; %inch,in sham room
ppd = atan2(wideScreen/2,distToScreen)*180/pi;%degree
ppd = windowRect(RectRight)/2/ppd; %pixels/degree
HideCursor;


%% Eyelink %%%%%%%%%%

% eyelink initialization and configuration
% if (Eyelink('InitializeDummy') ~= 0),
if (Eyelink('Initialize') ~= 0),
    fprintf('Problem initializing eyelink\n');
    return;
   
end
el = EyelinkInitDefaults();
% tell the Eyelink Host the coordinate space
if Eyelink('IsConnected') ~= el.notconnected,
    Eyelink('Command', 'screen_pixel_coords = %d %d %d %d', 0, 0, windowRect(RectRight), windowRect(RectBottom));
end
Eyelink('Command','calibration_type = HV5');
EyeLink('Command','file_event_filter = LEFT,RIGHT, FIXATION, SACCADE, BLINK, MESSAGE, INPUT');%sets which events will be written to the EDF file.
EyeLink('Command','link_event_filter = LEFT,RIGHT, FIXATION, INPUT'); %sets which types of events will be sent through link
EyeLink('Command','link_sample_data = LEFT,RIGHT, GAZE, AREA'); %sets data in samples sent through link

if isempty(edfFile)
    edfFile = 'data';
end
EyeLink('openfile', edfFile);


%% block loop

    randData = randPerm(numTrials); 
  
    
    %% set fixation duration
    
    randTime = randPerm(401)+ 799;
    
    fixDuration = randTime(1:numTrials);
 
    [numState,S,state, stateEvent,stateDuration,stateEndTime,stateStartTime] = stateInit_V3(numTrials,fixDuration);
    outData = repmat(1:numState,1,numTrials);
    outData = [outData,numState+1];
    vbl = zeros(numTrials*numState,1);
    %% set target type
   
    randTarget = randPerm(numTrials);
    targetType = rem(randTarget,2)+1;%for 2 target location [-10 10]
    
    ifi_duration = Screen('GetFlipInterval',winPtr);
    %ifi_duration = 0.0166742680706375;
    black = [0 0 0];
    %Draw background
    Screen('FillRect',winPtr,black,windowRect);
    Screen('Flip',winPtr);
    
    %% Eyelink %%%%%%%%%%
    %%calibrate the eye tracker
      
    el.backgroundcolour = 1;
    el.foregroundcolour = 225; 
    el.window = winPtr;
    status = eyelink('isconnected');
    if status == 0 %if not connected
        eyelink('closefile');
        eyelink('shutdown');
        return;
    end
    fprintf(' entered EyelinkDoTrackerSetup\n')
    error = EyelinkDoTrackerSetup(el, el.ENTER_KEY); % This calls the calibration,error: Screen( 'FillRect',  el.window, el.backgroundcolour );	% clear_cal_display()
    fprintf(' exited EyelinkDoTrackerSetup\n')

    %%%end calibration%%%%%
    
    
    %% %%%%%%%%%%
    eyelink('command','clear_screen %d',0);
    eyelink('command','draw_filled_box %d %d %d %d %d',round(windowRect(RectRight)/2-50),round(windowRect(RectBottom)/2-50),(windowRect(RectRight)/2+50),round(windowRect(RectBottom)/2+50),10);
    eyelink('command','draw_filled_box %d %d %d %d %d',round(windowRect(RectRight)/2 + ppd*10-50),round(windowRect(RectBottom)/2-50),(windowRect(RectRight)/2 + ppd*10+50),round(windowRect(RectBottom)/2+50),10);
    eyelink('command','draw_filled_box %d %d %d %d %d',round(windowRect(RectRight)/2 + ppd*(-10)-50),round(windowRect(RectBottom)/2-50),(windowRect(RectRight)/2 + ppd*(-10)+50),round(windowRect(RectBottom)/2+50),10);
    lptwrite(888,255)%Initialiaze DIN to 1,NetStation get "1" as no event;
    NetStation('Synchronize'); %do Synchronization with SynchLimit being 2.5ms
    eyelink('StartRecording');
    NetStation('StartRecording');
    
    %% pre-xp fixation
    pause(.5)
     Screen('DrawTextures',winPtr,coinTextureInd);
     Screen('Flip',winPtr); %absolute start time
     fprintf('\n\n\nwaiting for magnet to start...(press 5 to continue)\n\n')
buttons=0; % prevent from skipping mouse button loop
while buttons(1)==0  
    warning off MATLAB:DeprecatedLogicalAPI;
    [keyIsDown,secs,keyCode] = KbCheck; % Warning: mxSetLogical is deprecated and will not be supported in the future. Please refer to the Release Notes for information on updating your code
    warning on MATLAB:DeprecatedLogicalAPI;
    keyCode=find(keyCode,1);
    if keyCode==27% ESC on pcwin
        screen('Closeall');
        %simpleserial('close');
        disp('Task Aborted');
        return
    end    
    if keyCode==48+5% '5%' on pcwin the new mri trigger
        buttons=1;
    end    
    %     temp=simpleserial('bytesready'); % make sure to 
    %     if temp > sizeodata*2;
    %         data= simpleserial('read',floor(temp/sizeodata)*sizeodata,'int16');   
    %     end
end
%% start xp
    stateID = 1;trialID = 1;

    %draw the first fixation
    Screen('DrawTextures',winPtr,coinTextureInd);
    vbl(1) = Screen('Flip',winPtr); %absolute start time
    eyelink('message','trial start');
    lptwrite(888,255 - 2^(outData(stateID)-1));
    NetStation('Event',['evt' num2str(1)],vbl(1), stateDuration(1));
    absStartTime = vbl(1);
   
   
    while stateEvent(stateID)< S.ENDTASK
        switch stateEvent(stateID+1)
            case 1 %fixation
                trialID = floor((stateID+1)/numState)+1;
                %draw fixation
                Screen('DrawTextures',winPtr,coinTextureInd);             
            case 2 %blank screen
                Screen('FillRect',winPtr,black,windowRect);         
            case 3, %target
                %draw target if it is not catch trial
                
                locTarget = ppd*angleTarget(targetType(trialID));
                Screen('DrawTextures',winPtr,coinTextureInd,[], ...
                    [windowRect(RectRight)/2+locTarget-xCoin/2,windowRect(RectBottom)/2-yCoin/2,...
                    windowRect(RectRight)/2+locTarget+xCoin/2,windowRect(RectBottom)/2+yCoin/2]);
               
            case 4 %ISI
                Screen('FillRect',winPtr,black,windowRect);
            case 5 %end of task
                Screen('FillRect',winPtr,black,windowRect);
        end % switch
        %%while loop wait
        while getsecs - absStartTime < stateEndTime(stateID)
            
        end %while loop wait
        stateID=stateID+1;
        vbl(stateID) = Screen('Flip',winPtr);
        switch stateEvent(stateID) %messages
            case 1 %fixation
                eyelink('message','fixation on');
                
                
            case 2 %blank screen
                eyelink('message','blank screen');
                
            case 3 %target
                eyelink('message','target on');
                
            case 4 %ISI
                eyelink('message','ITI');
            case 5 %end of task
                eyelink('message','End of Task');
                
        end % switch  stateEvent(stateID) %messages
       lptwrite(888,255 - 2^(outData(stateID)-1));%each state/event set a corresponding DI of 8 bit parallel port to "0"
       NetStation('Event',['evt' num2str(stateEvent(stateID))],vbl(stateID),stateDuration(stateID));
    end %while stateEvent(stateID)< S.ENDTASK
    
    
    eyelink('StopRecording');
    NetStation('StopRecording');
    
% end;%blockID
%% say thankyou
%[winPtr,windowRect]=Screen('OpenWindow',1,[],[],pixelSize);
c_x=windowRect(3)/2;
c_y=windowRect(4)/2;
grey=[200 200 200]; % final color
temp=(grey-[0 0 0])./100;
for i = 1:100 % fade to grey algorythm
    Screen('FillRect',winPtr,round([0 0 0]+(temp*i)),windowRect);
    Screen('Flip',winPtr);
end  

screen('TextStyle',winPtr,1);% 0=plain, 1=bold, 2=italics, 3=1&2,  4=underlined, 5=4&1,6=4&2, 7=4&3. rem(?,8)
[oldFontName,oldFontNumber]=screen(winPtr,'TextFont','Tahoma');
screen('TextSize',winPtr,58);
ttext='thank you!';
%twidth=screen('TextWidth',winPtr,ttext);
tsize=Screen('TextBounds', winPtr, ttext);twidth=tsize(3);
screen('DrawText',winPtr,ttext,c_x-(twidth/2),c_y-60,[0 0 255]);
ttext='please rest.';
%twidth=screen('TextWidth',winPtr,ttext);
tsize=Screen('TextBounds', winPtr, ttext);twidth=tsize(3);
screen('DrawText',winPtr,ttext,c_x-(twidth/2),c_y+60,[0 0 255]);
screen('TextSize',winPtr,40);
screen('flip',winPtr);

pause(1);

Screen('CLoseAll')
ShowCursor;
eyelink('command', 'set_idle_mode');
waitsecs(0.5);
eyelink('CloseFile');
lptwrite(888,0);%clear parallel port
%% save parameter

 pathname = 'C:\_user\_hong\data';%uigetdir;%for sham room
%pathname = 'C:\Documents and Settings\Gunnar Blohm\My Documents\Hong\fasdxp1 data'; %for laptop
% pathname = 'C:\Documents and Settings\Hong Weng\My Documents\MATLAB\fasdxp1 data';%for my desktop
time = clock;%time = [year month day hour minute seconds]
filename =sprintf( '%s_fasdXP1_%d_%02d_%02d_%02dh%02dm.mat',edfFile, time(1),time(2),time(3),time(4),time(5));
save([pathname '\' filename],'vbl', 'fixDuration','targetType','xpType','state', 'stateEvent','stateDuration','stateEndTime','stateStartTime','numTrials','numState','angleTarget','distToScreen','wideScreen','ppd','windowRect')
disp('matlab parameter file saved')

%% download data file
% try
%     fprintf('Receiving data file ''%s''\n',edfFile);
%     status = eyelink('ReceiveFile');
%     if status > 0
%         fprintf('ReceiveFile status %d\n ', status);
%     end
%     if 2 == exist(edfFile, 'file')
%         fprintf('Data file ''%s'' can be found in '' %s\n',edfFile, pwd);
%     end
% catch
%     fprintf('Problem receiving data file ''%s''\n',edfFile);
% end

%close the eye tracker.
% status=Eyelink('ReceiveFile', edfFile ,pathname,1); % bcoe
% if status ~= 0
%     fprintf('problem: ReceiveFile status: %d\n', status);
% end
% disp('Transferring the data for you.')
% disp('done')
% disp('done, don''t forget copy edf file from eyelink computer')
Eyelink('ShutDown');


